﻿using IOA.MES.Client.Common;
using IOA.MES.Client.Models.Response;
using IOA.MES.Client.Settings;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Diagnostics;
using System.Reflection;

namespace IOA.MES.Client.LaminatorRework
{
    /// <summary>
    /// LaminatorIndex.xaml 的交互逻辑
    /// </summary>
    public partial class LaminatorReworkIndex :  System.Windows.Window
    {
        private WinScan winScan;
        private List<ViaSiteRecord> _records { get; set; } = new List<ViaSiteRecord>();
        private List<KeyValuePair<string, string>> lamireorks = new List<KeyValuePair<string, string>>();

        public LaminatorReworkIndex()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            txtTrueName.Text = BaseEnv.UserInfo.TrueName;
            InitDuties();
            InitMachines();
            InitRecords();
            InitBadReasons();
            LaReworkType.SelectedIndex = 0;

            //  InitForms();
            new TaskFactory().StartNew(() =>
            {
                Thread.Sleep(100);
                Dispatcher.Invoke(new Action(() =>
                {
                    winScan = new WinScan();
                    winScan.Closed += WinScan_Closed;
                    winScan.ShowDialog();
                }));
            });
        }

        #region 初始化数据
        public void InitDuties()
        {
            var duties = BaseEnv.InvokeApi<QueryDutiesResponse>("/api/Auth/QueryDuties", new { WorkshopCode = BaseEnv.WorkshopCode }).Data.Duties;

            cbDuties.ItemsSource = duties;
            cbDuties.DisplayMemberPath = "DutyName";
            cbDuties.SelectedValuePath = "DutyId";

            if (duties.Any())
            {
                cbDuties.SelectedIndex = 0;
            }
            //var badreasons = BaseEnv.InvokeApi<QueryBadReasonsResponse>("api/NQC/QueryBadReasons", new { ReasonType = 4 }).Data.BadReasons;

            //LaReworkReason.ItemsSource = badreasons;
            ////LaReworkReason.DisplayMemberPath = "";
            ////LaReworkReason.SelectedValuePath = "";

            //LaReworkType.SelectedIndex = 0;
        }

        public void InitMachines()
        {
            var machines = BaseEnv.InvokeApi<QueryMachinesResponse>("/api/Machine/QueryMachines", new { WorkshopCode = BaseEnv.WorkshopCode, MachineType = MachineType.LaminatorRework }).Data.Machines;
            cbMachines.ItemsSource = machines;
            cbMachines.DisplayMemberPath = "MachineName";
            cbMachines.SelectedValuePath = "MachineId";

            if (machines.Any(_ => _.MachineId == BaseEnv.MachineId))
            {
                cbMachines.SelectedIndex = machines.FindIndex(_ => _.MachineId == BaseEnv.MachineId);
            }
            else
            {
                CommonMessage.Alert(this, "请先在系统设置中重新选择设备\r\nPlease reselect the device in the system settings now"); ;
                new SettingsIndex().ShowDialog();
            }
        }

        private void InitRecords()
        {
            new TaskFactory().StartNew(() =>
            {
                Thread.Sleep(100);
                Dispatcher.Invoke(new Action(() =>
                {
                    var response = BaseEnv.InvokeApi<QueryViaSiteRecordsResponse>("/api/Machine/QueryViaSiteRecords", new { DutyId = Convert.ToInt32(cbDuties.SelectedValue), SiteType = SiteType.LaminatorRework, MachineId = Convert.ToInt32(cbMachines.SelectedValue) });
                    if (response.ErrCode != 200)
                    {
                        CommonMessage.Alert(this, response.ErrMsg);
                        return;
                    }
                    _records.Clear();
                    _records.AddRange(response.Data.Records);
                    _records.ForEach(_ => _.No = _records.Count - _records.IndexOf(_));
                    gridRecords.ItemsSource = null;
                    gridRecords.ItemsSource = _records;
                    lbTotal.Content = response.TotalCount;
                }));
            });
        }
        public void InitBadReasons()
        {
            
            var reasons = BaseEnv.InvokeApi<QueryBadReasonsResponse>("/api/NQC/QueryBadReasons", new { ReasonType = 4 }).Data.BadReasons;
            reasons.Insert(0, new BadReason());
            LaReworkReason.ItemsSource = reasons;
            LaReworkReason.DisplayMemberPath = "ReasonCN";
            LaReworkReason.SelectedValuePath = "ReasonCode";

            if (reasons.Any())
            {
                LaReworkReason.SelectedIndex = 0;
            }
        }

        #endregion

        private void WinScan_Closed(object sender, EventArgs e)
        {
            if (((WinScan)sender).DialogResult == true)
            {
                if (winScan.InspectData != null)
                {
                    txtCode.Text = winScan.InspectData?.ComponentData?.BarCode ?? string.Empty;
                    cbBadReason.Content = winScan.InspectData?.ComponentData ?.ReasonCN?? string.Empty;
                }
               
            }
        }

        /// <summary>
        /// 组件条码扫描
        /// </summary>
        private void txtCode_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Enter || string.IsNullOrWhiteSpace(txtCode.Text.Trim()))
            {
                return;
            }
            var txtBox = sender as TextBox;
            switch (txtBox.Name)
            {
                
                case "ReworkLocation":
                    LaReworkCellno.Focus();
                    break;
                case "LaReworkCellno":
                    var response = BaseEnv.InvokeApi<ViaSiteResponse>("/api/Machine/ViaSite", new
                    {
                        SiteType = SiteType.LaminatorRework,
                        DutyId = Convert.ToInt32(cbDuties.SelectedValue),
                        MachineId = Convert.ToInt32(cbMachines.SelectedValue),
                        BadCoordinates=LaReworkLocation.Text,
                        BadReason= LaReworkReason.SelectedValue,
                        Code = txtCode.Text.Trim()
                        
                    });
                    if (response.ErrCode != 200)
                    {
                        mediaElResult.Source = new Uri($"{BaseEnv.LocalDirectory}\\res\\audio\\Fail.wav");
                        mediaElResult.Play();
                        CommonMessage.Alert(this, response.ErrMsg);
                        InitForms();
                        return;
                    }
                    CommonMessage.Log(LogLevel.Info, $"过站成功：{txtCode.Text.Trim()}");

                    mediaElResult.Source = new Uri($"{BaseEnv.LocalDirectory}\\res\\audio\\Success.wav");
                    mediaElResult.Play();

                    //gridBoms.ItemsSource = null;
                    //gridBoms.ItemsSource = response.Data.Boms;

                    lbTotal.Content = response.Data.Output;
                    //cbWorkOrderNo.Content = response.Data.ViaSiteRecord.WorkOrderNo;

                    if (response.Data.DutyId != Convert.ToInt32(cbDuties.SelectedValue))
                    {
                        cbDuties.SelectedValue = response.Data.DutyId;
                    }
                    else
                    {
                        response.Data.ViaSiteRecord.No = _records.Count + 1;
                        _records.Insert(0, response.Data.ViaSiteRecord);
                        lamireorks.Add(new KeyValuePair<string, string>(LaReworkType.Name, LaReworkType.SelectedValue.ToString()));
                        lamireorks.Add(new KeyValuePair<string, string>(LaReworkReason.Name, string.IsNullOrEmpty(LaReworkReason.SelectedValue.ToString()) ? "" : LaReworkReason.SelectedValue.ToString()));
                        lamireorks.Add(new KeyValuePair<string, string>(LaReworkLocation.Name, LaReworkLocation.Text.ToString()));
                        lamireorks.Add(new KeyValuePair<string, string>(LaReworkCell.Name, LaReworkCell.Text.ToString()));
                        lamireorks.Add(new KeyValuePair<string, string>(LaReworkCellno.Name, LaReworkCellno.Text.ToString()));
                        gridRecords.ItemsSource = null;
                        gridRecords.ItemsSource = _records;
                    }
                    InitForms();
                    break;
            }


        }

        private void cb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            InitRecords();
        }

        private void InitForms(bool autoNext = true)
        {
            txtCode.Text = "";
            LaReworkCell.Text = "";
            LaReworkCellno.Text = "";
            LaReworkType.Text = "";
            LaReworkLocation.Text = "";
            new TaskFactory().StartNew(() =>
            {
                Dispatcher.Invoke(new Action(() =>
                {
                    
                    keyEnter = string.Empty;
                  
                    if (autoNext)
                    {
                        winScan = new WinScan();
                        winScan.Closed += WinScan_Closed;
                        winScan.ShowDialog();
                    }
                }));
            });
        }
        private string keyEnter = string.Empty;

        private void Menu_Click(object sender, RoutedEventArgs e)
        {
            switch (((MenuItem)sender).Name)
            {
                case "btnSettings":
                    new SettingsIndex().ShowDialog();
                    break;
                case "btnMissingRecords":
                    new MissingSiteRecord(Convert.ToInt32(cbMachines.SelectedValue)).Show();
                    break;
                case "btnLogout":
                    new LoginWindow(false).Show();
                    this.Hide();
                    break;
                case "btnAbout":
                    MessageBox.Show($"DehuiSolarMes Product Version:{FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion}");
                    break;
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
        }
    }
}
